package io.renren.modules.app.utils;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.CharArrayBuffer;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;

/**
 * 网络请求工具类
 *
 * @author weixiang
 * @date 2016-2-24 上午11:10:23
 * @copyright ©camore
 */
public class HttpClientUtils {

    public static void main(String[] args) {
        doPostSubmit();
    }

    /**
     * 作用：实现网络访问文件，先给服务器通过“POST”方式提交数据，再返回相应的数据
     * <p>
     * 默认有token
     *
     * @return 响应的实体类
     */
    public static Object doPostSubmit() {
        InputStream is = null;
        HttpClient httpClient = null;
        try {
            // ipad登录
//			String url = "http://192.168.18.8:8088/lucky/app/ipadLogin?username=admin&password=admin&device_id=111";
//			String jsonStr = "";
            // app修改密码  "userId":1,"token":"57708e42937b46e8b738f2fd25639a6d"
//			String url = "http://192.168.18.8:8088/lucky/app/updatePassword?user_id=1&pwd=666&token=57708e42937b46e8b738f2fd25639a6d";
//			String jsonStr = "";
            // app登录
//			String url = "http://39.98.235.159:8088/lucky/app/appLogin?username=13612083434&password=666";
//			String jsonStr = "";
            // app获取用户信息
//			String url = "http://192.168.18.8:8088/lucky/app/getUserInfo?user_id=1&token=36d7541f160840d687d7aafac8d018b6";
//			String jsonStr = "";
            // app资金详情列表
//			String url = "http://39.98.235.159:8088/lucky/app/getFinanceFlowList?user_id=1&token=cacc00b3f250499c84ede53e0d6b3433";
//			String jsonStr = "";
            // app增加资金
//			String url = "http://39.98.235.159:8088/lucky/app/addFinance?user_id=1&token=fced053025544505b3a028beca0b8496&finance_id=1"
//					+ "&finance_name=mingc&bug_fund=777&get_rate=7";
//			String jsonStr = "";
            // app用户每天理财
            String url = "http://192.168.18.8:8088/lucky/app/userFinanceRateByDay?flag=1&user_id=1&pageIndex=1"
                    + "&token=07ed4ca5c7614656ada0bd5c2bc7b593&pageCount=10";
            String jsonStr = "";
            url = url.replaceAll(" ", "%20");
            httpClient = getHttpClient();
            HttpPost requestPost = new HttpPost(url);
            requestPost.addHeader("Accept-Encoding", "gzip,deflate");
            /* 设置post体 */
            StringEntity entity = new StringEntity(jsonStr, "utf-8");// 解决中文乱码问题
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            requestPost.setEntity(entity);
            HttpResponse httpResponse = httpClient.execute(requestPost);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
                Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding");
                if (contentEncoding != null && contentEncoding.getValue().indexOf("gzip") >= 0) {
                    is = new GZIPInputStream(new BufferedInputStream(is));
                }
                String responseJsonStr = inputStream2String(is);
                System.out.println(responseJsonStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    static long old_time = System.currentTimeMillis();

    /**
     * 流转String
     *
     * @param in
     * @param m
     * @return
     * @throws IOException
     */
    public static String inputStream2String(InputStream in) throws IOException {
        // StringBuffer out = new StringBuffer();
        // byte[] b = new byte[4096];
        // for (int n; (n = in.read(b)) != -1;) {
        // out.append(new String(b, 0, n));
        // }
        CharArrayBuffer buffer = new CharArrayBuffer(4096);
        // Reader mReader = new Reader(in,"UTF-8");
        InputStreamReader reader = new InputStreamReader(in, "UTF-8");
        char tmp[] = new char[4096];
        int l;
        while ((l = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, l);
        }
        String s = buffer.toString();
        reader.close();
        return s;
    }

    /**
     * 得到HttpClient
     *
     * @return
     */
    public static HttpClient getHttpClient() {
        HttpParams httpParams = new BasicHttpParams();
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
        /* 设置最大连接数 */
        ConnManagerParams.setMaxTotalConnections(httpParams, 150);
        /* 设置从连接池获取连接的最大等待时间 */
        ConnManagerParams.setTimeout(httpParams, 1000);
        /* 设置每个路由最大连接数 */
        ConnPerRouteBean connPerRoute = new ConnPerRouteBean(80);
        ConnManagerParams.setMaxConnectionsPerRoute(httpParams, connPerRoute);
        /* 设置连接超时时间 */
        HttpConnectionParams.setConnectionTimeout(httpParams, 10 * 1000);
        /* 设置socket读取数据超时时间 */
        HttpConnectionParams.setSoTimeout(httpParams, 5 * 1000);
        HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
        /* 设置以Socket 缓存大小 */
        HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);
        /* 设置重定向，缺省为 true , 这里设置成不重定向 */
        HttpClientParams.setRedirecting(httpParams, false);
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        return httpClient;
    }

}
